public with sharing class WeekPlanCreatedExtension {
    public Weekly_Plan__c wpc {get;set;}
    public Event t {get;set;}
    public String rtSPId{get;set;}
    public String rtId{get;set;}
    public String rtHZId{get;set;}
    public String rtWpId{get;set;}
    public String strjson {get;set;}
    public String tabUrl;
    public String regioncode {get; set;}
    public Boolean isSeaOut {get;set;}//是否是海外销售
    private Id CamEventId;

    public WeekPlanCreatedExtension(ApexPages.StandardController con) {
        RecordType rtHZ=[select id from RecordType where  DeveloperName='Meeting'];
        RecordType rt=[select id from RecordType where  DeveloperName='Visit'];
        RecordType rtSP=[select id from RecordType where  DeveloperName='SalesPlanEdit'];
        RecordType rtWp = [select id from RecordType where  DeveloperName='WorkArrangement'];
         CamEventId= Utils.getRecordTypeIdByDevNameAndObjName('CamEvent', 'Event');
        rtSPId=rtSP.Id;
        rtId=rt.Id;
        rtHZId=rtHZ.Id;
        rtWpId = rtWp.Id;
        wpc=new Weekly_Plan__c();
        User u = [select AreaCode__c,Profile.Name from User where Id =:System.UserInfo.getUserId() ];
          regioncode = u.AreaCode__c;
        isSeaOut  = u.Profile.Name != null && u.Profile.Name.contains('海外');
      
        //regioncode = 'XS0102';
        t=new Event();

        PageReference page=System.currentPageReference();
        Map<String,String> pageMap=page.getParameters();
        tabUrl = pageMap.get('retURL');
        if(tabUrl == null){
            tabUrl = '/' + Weekly_Plan__c.sObjectType.getDescribe().getKeyPrefix() + '/o';
        }
    }  

    public WeekPlanCreatedExtension(){

        RecordType rtHZ=[select id from RecordType where  DeveloperName='Meeting'];
        RecordType rt=[select id from RecordType where  DeveloperName='Visit'];
        RecordType rtSP=[select id from RecordType where  DeveloperName='SalesPlanEdit'];
        RecordType rtWp = [select id from RecordType where  DeveloperName='WorkArrangement'];
         CamEventId= Utils.getRecordTypeIdByDevNameAndObjName('CamEvent', 'Event');
        rtSPId=rtSP.Id;
        rtId=rt.Id;
        rtHZId=rtHZ.Id;
        rtWpId = rtWp.Id;
        wpc=new Weekly_Plan__c();
        User u = [select AreaCode__c,Profile.Name from User where Id =:System.UserInfo.getUserId() ];
          regioncode = u.AreaCode__c;
        isSeaOut  = u.Profile.Name != null && u.Profile.Name.contains('海外');
      
        //regioncode = 'XS0102';
        t=new Event();

        PageReference page=System.currentPageReference();
        Map<String,String> pageMap=page.getParameters();
        tabUrl = pageMap.get('retURL');
        if(tabUrl == null){
            tabUrl = '/' + Weekly_Plan__c.sObjectType.getDescribe().getKeyPrefix() + '/o';
        }
    }

    public PageReference save(){
        Weekly_Plan__c wpInsert=new Weekly_Plan__c();

        System.debug(wpc);

        List<Weekly_Plan__c> wpcList=[select Id from Weekly_Plan__c where OwnerId=:System.UserInfo.getUserId() and End_Date__c>:wpc.Start_Date__c and Start_Date__c<:wpc.End_Date__c];
        if(!wpcList.isEmpty()){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR
                                                       ,'该周计划的时间与其他周计划存在重叠'));
            if(!System.Test.isRunningTest()){
                return null;
            }
        }
        try{

            wpInsert.Status__c = '草案中';
            wpInsert.Start_Date__c=wpc.Start_Date__c;
            wpInsert.End_Date__c=wpc.End_Date__c;
              wpInsert.Travel_Total__c=wpc.Travel_Total__c;
            wpInsert.Business_Total__c=wpc.Business_Total__c;
            /*wpInsert.Budget__c=wpc.Budget__c;

            wpInsert.Current_Travel__c=wpc.Current_Travel__c;
            wpInsert.Current_Business__c=wpc.Current_Business__c;
          
            wpInsert.RecordTypeId=rtSPId;

            wpInsert.CurrentTravelResult__c= wpc.CurrentTravelResult__c;
            wpInsert.CurrentBusinessResult__c=  wpc.CurrentBusinessResult__c;

            wpInsert.Travel_Budget__c= wpc.Travel_Budget__c;
            wpInsert.Business_Budget__c= wpc.Business_Budget__c;

            wpInsert.Travel_Result__c= wpc.Travel_Result__c;
            wpInsert.Business_Result__c= wpc.Business_Result__c; */

            Insert wpInsert;
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                                                       '操作出错：'+e.getMessage()));
            return null;
        }
        List<Event> taskIncomList=new List<Event>();
        System.debug('*** strjson: ' + strjson + '');
        List<Object> inJsonMap = (List<Object>)JSON.deserializeUntyped(strjson);
        System.debug(inJsonMap);
        for(Object obj : inJsonMap){
            Map<String,Object> objmap=(Map<String,Object>)obj;
            Event taskIncom=new Event();
            System.debug('*** objmap: ' + objmap + '');
            
                taskIncom.RecordTypeId=rtId;
                if(objmap.get('opp')+''!=''){//业务机会
                    taskIncom.WhatId=Id.valueOf(String.valueOf(objmap.get('opp')));
                    taskIncom.Opportunity__c=String.valueOf(objmap.get('opp'));
                }/*else if(objmap.get('acc')+''!= ''){
                       // taskIncom.WhatId=String.valueOf(objmap.get('acc'));
                        System.debug('*** opp: ' + String.valueOf(objmap.get('acc'))+ '');
                        taskIncom.Opportunity__c=null;
                    }else {
                         taskIncom.WhatId=null;
                         taskIncom.Opportunity__c=null;
                    }*/
                if(objmap.get('con')+''!=''){//联系人
                    taskIncom.Contact__c = String.valueOf(objmap.get('con'));
                    //taskIncom.WhoId=String.valueOf(objmap.get('con'));
                }/*else{
                        taskIncom.WhoId=null;
                    }*/
                if(objmap.get('acc')+'' != ''){
                    taskIncom.Account__c=String.valueOf(objmap.get('acc'));   
                }else {

                    taskIncom.Account__c=null;

                }
            

            taskIncom.Status__c= '未开始';

            taskIncom.Subject=String.valueOf(objmap.get('sub'));
            taskIncom.Type=String.valueOf(objmap.get('type'));
            taskIncom.Work_Address__c=String.valueOf(objmap.get('address'));
            taskIncom.StartDateTime    =DateTime.valueOf(''+objmap.get('startvisitdate')+':00');
            taskIncom.EndDateTime=DateTime.valueOf(''+objmap.get('endvisitdate')+':00');
            taskIncom.Travel_Fee__c=0;
            taskIncom.Busness_Fee__c=0;
            taskIncom.AccountBudget__c=0;
            taskIncom.AccountBudgetUsed__c=0;

            if(String.valueOf(objmap.get('type')).equals('参加展会')){
                taskIncom.RecordTypeId=rtHZId; 
            }
            if(String.valueOf(objmap.get('type')).equals('例行拜访/沟通') || String.valueOf(objmap.get('type')).equals('回款拜访/沟通') || String.valueOf(objmap.get('type')).equals('销售拜访/沟通')){
                taskIncom.RecordTypeId=rtId; 
            }
            if(String.valueOf(objmap.get('type')).equals('培训学习') || String.valueOf(objmap.get('type')).equals('整理资料') || String.valueOf(objmap.get('type')).equals('内部会议')){
                taskIncom.RecordTypeId=rtWpId ; 
            }
            if(String.valueOf(objmap.get('type')).equals('市场沟通')
             || String.valueOf(objmap.get('type')).equals('意向') 
             || String.valueOf(objmap.get('type')).equals('合作细节谈判')
             || String.valueOf(objmap.get('type')).equals('提起合作确认')
             || String.valueOf(objmap.get('type')).equals('市场管理')){
                taskIncom.RecordTypeId=CamEventId ; 
            }




            if(objmap.get('tf')+''!='')
            {
                taskIncom.Travel_Fee__c=Double.valueOf(objmap.get('tf'));
            }
            if(objmap.get('bf')+''!='')
            {
                taskIncom.Busness_Fee__c=Double.valueOf(objmap.get('bf'));
            }

            if(objmap.get('accBudget') +''!=''){
                taskIncom.AccountBudget__c =Double.valueOf(objmap.get('accBudget'));
            }

            if(objmap.get('accBudgetUsed') +''!=''){
                taskIncom.AccountBudgetUsed__c =Double.valueOf(objmap.get('accBudgetUsed'));
            }
            taskIncom.Week_Plan__c=wpInsert.Id;

            //设置活动来自周计划
            taskIncom.FromWeeklyPlan__c=true;

            System.debug('Week_Plan__c==>'+taskIncom);
            taskIncomList.add(taskIncom);

        }
        try{
            System.debug('*** taskIncomList: ' + taskIncomList + '');
            Insert taskIncomList;

        }catch(Exception e){
            delete wpInsert;
            ApexPages.addMessage(
                new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage()));
            return null;
        }


        return new PageReference('/'+wpInsert.Id);
    }
    public PageReference cancle(){
        return new PageReference(tabUrl);
    }
}